import { buildQuery } from '../utils/util';
import host from '../config/host';
export function get(path, params, callback, otherHost=null) {
    params = params || {};
    params.token = localStorage.getItem('token');
    let query = buildQuery(params);
    let url = null;
    if(otherHost !== null){
        url = otherHost + path + '?' + query;
    }else{
        url = host.host + path + '?' + query;
    }

    fetch(url, {
        method: 'GET',
        credentials: 'include',
        headers: { 'content-Type': 'application/x-www-form-urlencoded' }
    })
        .then(function(res) {
            if (res.ok) {
                let result = res.json();
                return result;
            } else {
                console.warn('[net]服务器出错了');
                throw '服务器出错了，请稍后重试';
            }
        })
        .then(function(json) {
            console.log('request response : ' + path, json);
            if (json.error === undefined) {
                callback(null, json);
            } else {
                let msg = json.error;
                callback(msg , null);
            }
        })
        .catch(function(err) {
            callback(err, null);
        });
}

export function post(path, params, callback) {
    params = params || {};
    params.token = localStorage.getItem('token');
    let query = buildQuery(params);
    let url = host.host + path;
    if (path.startsWith('http')) {
        url = path;
    }
    console.log('url: ', url);

    fetch(url, {
        method: 'POST',
        credentials: 'include',
        headers: { 'content-Type': 'application/x-www-form-urlencoded' },
        body: query
    })
        .then(function(res) {
            if (res.ok) {
                let result = res.json();
                return result;
            } else {
                console.warn('[net]服务器出错了');
                throw '服务器出错了';
            }
        })
        .then(function(json) {
            console.log('request response : ' + path, json);
            if (json.error === undefined) {
                callback(null, json);
            } else {
                let msg = json.error;
                callback(msg , null);
            }
        })
        .catch(function(err) {
            callback(err, null);
        });
}
